import Vue from 'vue'
import router from './router'
import store from './store'
import storage from './utils/storage'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import {isEmpty} from 'lodash'
import utils from './utils'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const allowList = ['login', 'register', 'registerResult'] // no redirect allowList
const loginRoutePath = '/user/login'
const defaultRoutePath = '/dashboard/workplace'
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)
  if (storage.get(ACCESS_TOKEN)) {
    if (to.path === loginRoutePath) {
      next()
      NProgress.done()
    } else {
      if (isEmpty(store.getters.userInfo)) {
        store
        .dispatch('getUserInfo')
        .then(userPermissions => {
          // utils.getAllDict()
          // store.dispatch('GenerateRoutes', userPermissions).then(() => {
          //   store.getters.addRouters.forEach(r => {
          //     router.addRoute(r)
          //   })
          //   next(to.path)
          // })
          if (store.getters.userInfo.permissionIds.length === 0) {
            next('/NOpermissions')
          } else {
            // utils.getAllDict()
            store.dispatch('GenerateRoutes', userPermissions).then(() => {
              // store.getters.addRouters = store.getters.userInfo.permissionIds
              store.getters.addRouters.forEach(r => {
                router.addRoute(r)
              })
              next(to.path)
            })
          }
        })
      } else {
        next()
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

// 按钮权限验证方法
Vue.prototype.$permissionJudge = permissionId => {
  // 将vuex里面的变量保存到window对象下 防止多次调用该方法多次获取
  if (window.__USER_PERMISSIONS__ instanceof Array) {
    return window.__USER_PERMISSIONS__.includes(permissionId)
  }
  // 不是数组直接返回false
  return false
}
